package serverlet.pay;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.thor.palmmall.api.statement.AStatementPayBill;
import com.thor.palmmall.api.statement.AStatementPayBillState;
import com.thor.palmmall.api.statement.StatementService;
import com.thor.palmmall.rest.event.StatementOrderSyncEvent;
import com.thor.palmmall.util.event.GlobalEventBus;
import com.thor.palmmall.util.pay.ChinaPayUtil;

public class ChianPayCallbackServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private final String NOTIFY_FLAG_SUCCESS = "success";
  StatementService statementService;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public ChianPayCallbackServlet() {
    super();
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doPost(request, response);
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    // 解析 返回报文
    Enumeration<String> requestNames = request.getParameterNames();
    Map<String, String> resultMap = new HashMap<String, String>();
    while (requestNames.hasMoreElements()) {
      String name = requestNames.nextElement();
      String value = request.getParameter(name);
      value = URLDecoder.decode(value, "UTF-8");
      resultMap.put(name, value);
    }
    AStatementPayBill bill = statementService.getByBillNumber(resultMap.get("MerOrderNo"));
    if (bill != null) {
      // 验证签名
      if (ChinaPayUtil.verify(bill, resultMap)) {
        String orderStatus = resultMap.get("OrderStatus");
        if ("0000".equals(orderStatus)) {
          processStatementBill(resultMap);
          response.getWriter().write("success");
        }
      }
    }
    response.getWriter().write("fail");
  }

  /**
   * 处理对账单
   * 
   * @param resultMap
   */
  public void processStatementBill(Map<String, String> resultMap) {
    try {
      AStatementPayBill bill = statementService.getByBillNumber(resultMap.get("MerOrderNo"));
      bill.setState(AStatementPayBillState.PAID);
      bill.setNotifyFlag(NOTIFY_FLAG_SUCCESS); // 回调使用单独的标志字段
      bill.setTransactioNo(resultMap.get("AcqSeqId"));// 收单流水号
      bill.setBuyerLogonId(resultMap.get("BankInstNo"));// 支付机构号
      bill.setSellerEmail(resultMap.get("MerId"));
      String tranDate = resultMap.get("TranDate") + resultMap.get("TranTime");
      bill.setActionTime(new SimpleDateFormat("yyyyMMddhhmmss").parse(tranDate));// 交易日期
      statementService.saveStatementPayBill(bill, bill.getCreateInfo());
      // 开始同步订单任务
      StatementOrderSyncEvent event = new StatementOrderSyncEvent();
      event.setBill(bill);
      GlobalEventBus.post(event);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  public void init(ServletConfig servletConfig) throws ServletException {
    WebApplicationContext wac = WebApplicationContextUtils
        .getRequiredWebApplicationContext(servletConfig.getServletContext());
    statementService = wac.getBean(StatementService.class);
  }

}
